
// Copyright (C) 2007 Richard Uhler
// This file is part of Esiply.
//
// Esiply is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <assert.h>

#include "Completion.h"
#include "HostContext.h"
#include "HostValue.h"
#include "EvalFunction.h"
#include "List.h"
#include "String.h"
#include "Undefined.h"

Value* EvalFunction::call(Scope* scope, Value* this_obj, List* args)
{
    if (args->empty())
    {
        return Undefined::undefined;
    }

    // Ecma 15.1.2.1 eval(x)
    // 1. If it's not a string, return it
    if (args->get(0)->getType() != VT_STRING)
    {
        return args->get(0);
    }

    // 2. Parse x as a Program.
    // 3. Evaluate that program.
    HostContext hc(scope);
    Value* res = hc.host_eval(args->get(0)->string()->c_str()).get_value();

    // 4. If res.type is normal and its completion value is a value V,
    // then return the value V.
    // TODO: 5. If res.type is normal and value is empty, then return the value
    // undefined.
    if (res->completion()->type() == CT_NORMAL)
    {
        return res->completion()->value();
    }

    // 6. Res.type must be throw. Throw it.
    return res;
}

Value* EvalFunction::construct(List* args)
{
    // TODO: do something meaningful here.
    assert(false);
    return NULL;
}

